import axios from "axios";
import router from '../router';
import Message from "element-ui/packages/message/src/main";

axios.defaults.baseURL = process.env.VUE_APP_BASEURL;
const instance = axios.create({ timeout: 1000 * 30 });

// 请求拦截器
instance.interceptors.request.use(config => {
    config.headers["Content-Type"] = "application/json;charset=utf-8";
    if (sessionStorage.getItem('userInfo')) {
        config.headers["token"] = JSON.parse(sessionStorage.getItem('userInfo')).token;
    }
    return config;
},error => {
    Message.error({message:"请求超时!"})
    return Promise.resolve(error)
});

// 响应拦截器
instance.interceptors.response.use(response => {
    if (response.data.code === 401) {
        router.push({ name: "Login" });
        Message.error({message: response.data.data})
    }
    if (response.data.code === 500) {
        Message.error({message: response.data.msg})
    }
    if (response.data.code === 501) {
        Message.error({message: response.data.data})
    }
    return response;
},
 error => {
    Message.error({message: `请求响应异常!${error}`})
     return Promise.resolve(error)
 });



export default instance;
